﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using KC.ExtensionMethods;

namespace KC.Business.Web
{
	public class RequestTools
	{
		public static bool isSearchEngineReferral(Uri Referrer, out string Engine, out string Query)
		{
			Engine = null;
			Query = null;

			if (Referrer == null || string.IsNullOrEmpty(Referrer.AbsoluteUri) || !Referrer.AbsoluteUri.Contains('?'))
				return false;

			System.Collections.Specialized.NameValueCollection QueryString = HttpUtility.ParseQueryString(Referrer.AbsoluteUri.Replace("?", "?randomxx-8f8d989af&"));
			string QueryMember = "";
			Engine = Referrer.GetRootDomain().ToLower();
			if (Engine.Contains('.')) Engine = Engine.Substring(0, Engine.IndexOf('.')).Trim();
			switch (Engine)
			{	
				case "google":
				case "live":
				case "msn":
				case "altavista":
				case "search":
				case "ask":
				case "cuil":
				case "bing":
					QueryMember = "q";
					break;
				case "yahoo":
					QueryMember = "p";
					break;
				case "lycos":
				case "business":
				case "aol":
				case "netscape":
				case "clusty":
					QueryMember = "query";
					break;
				case "baidu":
					QueryMember = "wd";
					break;
			}

			if (string.IsNullOrEmpty(QueryMember) || !Referrer.AbsoluteUri.Contains(QueryMember + "="))
				return false;
			if (Engine.Contains('.'))
				Engine = Engine.Substring(0, Engine.IndexOf('.'));

			Query = HttpUtility.UrlDecode(QueryString[QueryMember].Trim());
			return true;
		}

	}
}
